<?php
function loadGlobalParameters() {//TODO load real values....
	global $lang_id, $languages_list, $manufacturer_list, $supplier_list;
	$lang_id = 0;
	$languages_list = array(
		0 => 'English',
		1 => 'Français'
	);
	$manufacturer_list = array(
		3 => 'Apple',
		7 => 'Logitech'
	);
	$supplier_list = array(
		10 => 'Apple',
		15 => 'La redoute'
	);
}

function empty_container($container)
{
	$old_children = $container->get_children();
	foreach ($old_children as $old_child)
		$container->remove($old_child);
}

function empty_combobox($combobox)
{
	$old_children = $combobox->get_children();
	foreach ($old_children as $key => $old_child)
		$combobox->remove_text($key);
}

function _loadList($widget_ids, $data)
{
	global $glade;
	foreach ($widget_ids as $widget_id)
	{
		$widget = $glade->get_widget($widget_id);
		empty_combobox($widget);
		foreach ($data as $id_item => $item_name)
			$widget->insert_text($id_item, $item_name);
	}
}

function loadManufacturersList($widget_ids)
{
	global $glade, $manufacturer_list;
	_loadList($widget_ids, $manufacturer_list);
}

function loadSuppliersList($widget_ids)
{
	global $glade, $supplier_list;
	_loadList($widget_ids, $supplier_list);
}

function loadLanguagesList($widget_ids)
{
	global $glade, $languages_list;
	_loadList($widget_ids, $languages_list);
}

function loadCatalogList($catalog_listing, $tree_data, $selected_categories) {
	empty_container($catalog_listing);
	
	if (defined("GObject::TYPE_STRING"))
		$store = new GtkTreeStore(GObject::TYPE_BOOLEAN, GObject::TYPE_STRING);
	else
		$store = new GtkTreeStore(Gtk::TYPE_BOOLEAN, Gtk::TYPE_STRING);
	$view = new GtkTreeView($store);
	$view->append_column(
		new GtkTreeViewColumn('Categorie', new GtkCellRendererText(), 'text', 1)
	);
	$cell_renderer = new GtkCellRendererToggle();
	$cell_renderer->set_property('activatable', true);
	$column = new GtkTreeViewColumn('Select', $cell_renderer, 'active', 0); // note 2
	$cell_renderer->connect('toggled', 'on_toggle_category_state', $store); // note 3
	$view->append_column($column);
	$nodes = array();
	
	foreach($tree_data as $node_data) {
		$node_data[] = in_array($node_data[0], $selected_categories) ? 1 : 0;
		$parent_node = isset($nodes[$node_data[1]]) ? $nodes[$node_data[1]] : null;
		$nodes[$node_data[0]] = $store->append($parent_node, array($node_data[3], $node_data[2]));
	}
	$view->expand_all();
	$catalog_listing->add($view);
	$catalog_listing->show_all();
}

function on_toggle_category_state($renderer, $row, $model) {
    $iter = $model->get_iter($row); // note 6
    $model->set($iter, 0, !$model->get_value($iter, 0)); // note 7
}
